package edu.itstudy.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBConUtil {
	private static Connection conn=null;
	private static String url="jdbc:mysql://localhost:3306/user?useSSL=false&serverTimezone=GMT%2B8";
	private static String user = "root";
	private static String password = "1234";
	private static String className = "com.mysql.cj.jdbc.Driver";
	
	
	//加载数据驱动
	static{
		try{
			Class.forName(className);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	
	//获取数据库连接
	public static Connection getConn() {
		synchronized (DBConUtil.class) {
			try {
				if(null == conn || conn.isClosed()) {
					synchronized (DBConUtil.class) {
						try {
							conn =DriverManager.getConnection(url, user, password);
						}catch(SQLException e) {
							e.printStackTrace();
						}
					}
				}
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	//关闭连接
	public static void closeConn(ResultSet rs,Statement st,PreparedStatement pst,Connection conn) {
		try {
		if(null != rs) {
			rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != st) {
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				try {
					if(null != pst) {
						pst.close();
					}
				}catch(SQLException e) {
					e.printStackTrace();
				}finally {
					try {
						if(null != conn && !conn.isClosed()) {
							conn.close();
							}
						}catch(SQLException e) {
							e.printStackTrace();
					}
				}
			}
		}
	}
}
